package com.liwenfeng.huangputi;

import java.util.ArrayList;
import java.util.Optional;
import java.util.Random;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

/*
 * 集合、Stream流练习题：
 * 生成1-200的随机编号给100个囚犯，并生成编号的顺序排队，杀掉奇数位（位置从1开始）的囚犯，直到剩下一个囚犯，
 * 输出剩下的囚犯编号和第一次排队时的位置编号
 * */
public class Answer {
    Random random = new Random();
    ArrayList<Prisoner> list = new ArrayList<>();

    public Answer() {
        for (int i = 0; i < 100; ) {
            int num = random.nextInt(1, 201);
            Optional<Prisoner> any = list.stream().filter(item -> item.getCode() == num).findAny();
            if (any.isEmpty()) {
                list.add(new Prisoner(num, i + 1));
                i++;
            }
        }
        System.out.println(list.toString() + "========" + list.size());
    }

    public Prisoner kill() {
        while (list.size() > 1) {
            //方法1：保存活着的囚犯
//            ArrayList<People> list1 = new ArrayList<>();
//            for (int i = 1; i < list.size(); i+=2) {
//                list1.add(list.get(i));
//            }
//            list = list1;

            //方法2：用迭代器删除被杀掉的囚犯
//            Iterator<Prisoner> it = list.iterator();
//            int i = 1;
//            while (it.hasNext()) {
//                it.next();
//                if (i++ % 2 == 1) it.remove();
//            }

            //方法3：Stream流
            AtomicInteger i = new AtomicInteger(1);
            list = (ArrayList<Prisoner>) list.stream().filter(item -> i.getAndIncrement() % 2 != 1).collect(Collectors.toList());
            System.out.println(list.toString() + "========" + list.size());
        }
        return list.get(0);
    }

    public static void main(String[] args) {
        Prisoner prisoner = new Answer().kill();
        System.out.println("幸存的囚犯编号为：" + prisoner.getCode() + "，他第一次的位置为：" + prisoner.getLocation());
    }

}
